﻿using FibMatrix.DS;
using FibMatrix.Schedule;
using FibMatrix.Task;
using FM_Mono;

namespace FibMatrix
{
    [IgnoreGen]
    public class PooledCallLaterFMTask : FMTask
    {
        private static ObjectPool2<PooledCallLaterFMTask> _pool = new ObjectPool2<PooledCallLaterFMTask>(-1, () => new PooledCallLaterFMTask(), false);

        public int frames
        {
            get;
            set;
        }

        private int _updator;

        private PooledCallLaterFMTask() : base("PooledCallLaterRETask ", false)
        {

        }

        public static PooledCallLaterFMTask Allocate(int frames = 1)
        {
            var task = _pool.Allocate();
            task.frames = frames;
            return task;
        }

        protected override void DoAction()
        {
            this._updator = GlobalScheduler.CallOnceFrame(this.frames, this.OnDownloadComplete);
        }

        private void OnDownloadComplete(object context)
        {
            if (!GlobalScheduler.IsValid(this._updator))
            {
                return;
            }
            this._updator = -1;
            this.ApplyComplete();
        }

        protected override void DoAbort()
        {
            base.DoAbort();
            GlobalScheduler.RemoveLimitUpdator(ref this._updator);
        }

        protected override void DoDispose()
        {
            base.DoDispose();
            _pool.Recycle(this);
        }
    }
}
